
/************************************************************************
* Array implemented as a Queue
* GSP295 Week2 iLab: FIFO Queue
* Author: Ronald Ram
************************************************************************/


#include "QueueArray.h"

namespace GSP295_Wk2
{
	//C001: Default Constructor
	QueueArray::QueueArray()
	{ 
		capacity = 5;
		Init();
	}

	
	//C004: Init data array
	void QueueArray::Init()
	{
		back = front = size = 0;
		data = new string[capacity];
		for (int i=0; i< capacity; ++i) { data[i] = ""; }
	}

	
	//C003: Destructor
	QueueArray::~QueueArray()
	{
		delete [] data;
		back = front = size = 0;
		capacity = 10;
	}

	
	//M001: Add element to BACK of Queue
	bool QueueArray::Enqueue( string item )
	{
		if ( !isFull() )
		{
			data[size] = item;
			front = 1;
			++size;  ++back;
			return true;
		} 
		else { return false; }
	}

	
	//M002: Remove element from front of Queue
	bool QueueArray::Dequeue( string& output )
	{
		if ( !isEmpty() ) 
		{
			output = data[front-1];

			//2+ elements in array 
			if ( (size-1) != 0 ) 
			{
				string *temp = new string[capacity];

				//Create temp array
				for ( int i=0; i< capacity; ++i ) { temp[i] = ""; }
				//Transfer data[] -> temp[]
				for ( int j= front; j< capacity; ++j) { temp[j-1] = data[j]; }

				delete [] data;
				data = new string[capacity];

				//instantiate data[] again
				for ( int l=0; l< capacity; ++l ) { data[l] = ""; }
				//Transfer temp[] -> data[]
				for ( int m=0; m< capacity; ++m) { data[m] = temp[m]; }

				//decrement size and reposition back
				--size;
				--back;
			}
			//ONLY 1 element in array
			else 
			{
				delete [] data;
				Init();
			}

			return true;
		} 
		//array is empty
		else { output = "Queue is Empty";  return false; }
	}

	
	//M003: Check if Queue is Empty
	bool QueueArray::isEmpty() const { return (size == 0); }

	
	//M004: Check if Queue is Full
	bool QueueArray::isFull() const { return (size == capacity); }

	
	//M005: Remove all elements from Queue
	void QueueArray::Clear()
	{
		delete [] data;
		Init();
	}

	
	
	//M006: Print all elements in Queue
	void QueueArray::Print()
	{
		if ( isEmpty() ) 
		{ 
			cout << "\nRESULT: FIFO Queue is Empty" << endl;
		} 
		else 
		{
			cout << "\nFIFO Queue Results" << endl;
			cout << "--------------------------------" << endl;
			for (int i=0; i< size; ++i) 
			{
				cout << "[" << i << "] = " << data[i] << endl;
			}
		}	
		cout << "\n======================================\n\n\n" << endl;
	}
};
